package com.ugoodtech.mdcc.web.service.impl;

import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.ArrayStringUtil;
import com.ugoodtech.mdcc.core.utils.BaseUtil;
import com.ugoodtech.mdcc.core.utils.FieldArrayUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.service.OutSideUserService;
import com.ugoodtech.mdcc.web.service.UserLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import org.springframework.util.CollectionUtils;

@Service
public class OutSideUserServiceimpl implements OutSideUserService {

    private static final Logger logger = LoggerFactory.getLogger(OutSideUserServiceimpl.class);

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private PerformanceReportRepository performanceReportRepository;
    @Autowired
    private PerformanceReportDetailRepository performanceReportDetailRepository;
    @Autowired
    private PerformanceReportRecordRepository performanceReportRecordRepository;

    @Override
    public JsonResponse addSystemUser(String userType, String serialNumber, String name, String telephone,
                                      String departmentIds, String proinces, String proincesAndBrands, String stationIds, String authorities, String brands, Boolean isAdmin) {
        logger.info("userType:" + userType);
        logger.info("serialNumber:" + serialNumber);
        logger.info("name:" + name);
        logger.info("telephone:" + telephone);
        logger.info("deparmentIds:" + departmentIds);
        logger.info("proinces:" + proinces);
        logger.info("proincesAndBrands:" + proincesAndBrands);
        logger.info("stationIds:" + stationIds);
        logger.info("authorities:" + authorities);

        User user = userRepository.findByUserName_phone(telephone);
        UserProfile userProfile = userProfileRepository.findByTelephone(telephone);
        JsonResponse isCreated;
        User userNew = new User();
        UserProfile userProfileNew = new UserProfile();

        if (StringUtils.isNotEmpty(serialNumber)) {
            if (userProfile != null && userProfile.getSerialNumber() != null) {
                return JsonResponse.errorResponseWithError("抱歉", "此员工编号已经存在");
            }
        }else {
            return JsonResponse.errorResponseWithError("抱歉", "员工编号不能为空");
        }
        if (!StringUtils.isNotEmpty(telephone)) {
            return JsonResponse.errorResponseWithError("抱歉", "手机号码不能为空");
        }
        if (user != null) {
            if (user.getUserFlag() != 1){
                return JsonResponse.errorResponseWithError("抱歉", "此手机号码已经存在");
            }else {
                //TODO 更新用户
                isCreated = create_saveUser(user, userProfile, userType, serialNumber, name, telephone,
                        departmentIds, proinces, proincesAndBrands, stationIds, authorities, brands, isAdmin);
            }
        }else {
            //new出用户对象
            isCreated = create_saveUser(userNew, userProfileNew, userType, serialNumber, name, telephone,
                    departmentIds, proinces, proincesAndBrands, stationIds, authorities, brands, isAdmin);
            if (null == isCreated) {
                return JsonResponse.errorResponseWithError("抱歉", "用户创建失败");
            }
        }
        return isCreated;
    }


    @Override
    public JsonResponse editSystemUser(Long userProfileId, String userType, String serialNumber, String name, String telephone,
                                       String departmentIds, String proinces, String proincesAndBrands, String stationIds, String authorities, String brands, Boolean isAdmin, User currentUser) {
        logger.info("userProfileId:" + userProfileId);
        logger.info("userType:" + userType);
        logger.info("serialNumber:" + serialNumber);
        logger.info("name:" + name);
        logger.info("telephone:" + telephone);
        logger.info("deparmentIds:" + departmentIds);
        logger.info("proinces:" + proinces);
        logger.info("proincesAndBrands:" + proincesAndBrands);
        logger.info("stationIds:" + stationIds);
        logger.info("authorities:" + authorities);
        UserProfile userProfile = userProfileRepository.findOne(userProfileId);
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        if (!userProfile.getSerialNumber().equals(serialNumber)) {
            if (userProfileRepository.isSameSerialNumber(userProfileId, serialNumber) != null) {
                return JsonResponse.errorResponseWithError("抱歉", "此编号已经被使用");
            }
        }
        if (!userProfile.getTelephone().equals(telephone)) {
            List<UserProfile> userProfile1 = userProfileRepository.findUsersByTelephone(telephone);
            if (!CollectionUtils.isEmpty(userProfile1)) {
                return JsonResponse.errorResponseWithError("抱歉", "此手机号码已经被使用");
            }
        }

        User user = userProfile.getUser();

        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户的登陆信息");
        }
        if (!userProfile.getTelephone().equals(user.getUsername())) {
            userProfile.setTelephone(user.getUsername());
            userProfileRepository.save(userProfile);
        }
        Map<String, Object> data = null;
        try {
            data = new HashMap<>();
            String desc = "姓名:" + userProfile.getRealName() + ",";
            if (!userType.equals(user.getUserType().name())) {
                desc += "类型 :";
                desc += user.getUserType().name() + "-->>" + userType + ",";
            }
            if (!serialNumber.equals(userProfile.getSerialNumber())) {
                desc += "员工编号 :";
                desc += userProfile.getSerialNumber() + "-->>" + serialNumber + ",";
            }
            if (!name.equals(userProfile.getRealName())) {
                desc += "姓名 :";
                desc += userProfile.getRealName() + "-->>" + name + ",";
            }
            if (!telephone.equals(userProfile.getTelephone())) {
                desc += "手机号码 :";
                desc += userProfile.getTelephone() + "-->>" + telephone + ",";
            }
            String changeName = getModelNames(departmentIds, departmentRepository, "totalName");
            String originName = FieldArrayUtil.getFieldStr(userProfile.getDepartmentList(), "totalName");
            if (!changeName.equals(originName)) {
                desc += "部门 :";
                desc += originName + "-->>" + changeName + ",";
            }
            String changeProvince = getModelProvinceStr(proinces, nationRepository, "province");
            String originProvince = FieldArrayUtil.getFieldStr(userProfile.getNationList(), "province");
            if (!changeProvince.equals(originProvince)) {
                desc += "省份 :";
                desc += originProvince + "-->>" + changeProvince + ",";
            }
            if (!proincesAndBrands.equals(userProfile.getProincesAndBrands())) {
                desc += "负责省份品牌 :";
                desc += userProfile.getProincesAndBrands() + "-->>" + proincesAndBrands + ",";
            }
            String changeStations = getModelNames(stationIds, stationRepository, "name");
            String originStations = FieldArrayUtil.getFieldStr(userProfile.getStationList(), "name");
            if (!proincesAndBrands.equals(userProfile.getProincesAndBrands())) {
                desc += "维修站:";
                desc += originStations + "-->>" + changeStations + ",";
            }
            String changeAuthorities = getModelNames(authorities, moduleAuthorityRepository, "description");
            String originAuthorities = FieldArrayUtil.getFieldStr(userProfile.getUser().getAuthorities(), "description");
            boolean changeFlag = false;
            List<String> changeAuthoritiesArray = Arrays.asList(changeAuthorities.split(","));
            List<String> originAuthoritiesArray = Arrays.asList(originAuthorities.split(","));
            Collections.sort(changeAuthoritiesArray);
            Collections.sort(originAuthoritiesArray);
            changeAuthorities = StringUtils.join(changeAuthoritiesArray, ",");
            originAuthorities = StringUtils.join(originAuthoritiesArray, ",");
            if (!originAuthorities.equals(changeAuthorities)) {
                desc += "功能权限 :";
                desc += originAuthorities + "-->>" + changeAuthorities + ",";
            }

            String changeBrands = getModelNames(brands, brandRepository, "brandName");
            String originBrands = FieldArrayUtil.getFieldStr(userProfile.getBrandList(), "brandName");
            if (!originBrands.equals(changeBrands)) {
                desc += "负责的品牌 :";
                desc += originBrands + "-->>" + changeBrands + ",";
            }

            data.put("str", desc);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JsonResponse isSaved = create_saveUser(user, userProfile, userType, serialNumber, name, telephone,
                departmentIds, proinces, proincesAndBrands, stationIds, authorities, brands, isAdmin);
        if (isSaved.isSuccess()) {
            if (!("姓名:" + userProfile.getRealName()).equals(data.get("str"))) {
                userLogService.addUserLog(currentUser, null, LogConstants.operate_type_edit, LogConstants.business_type_system_user, null, data);
            }
            return isSaved;
        }
        return isSaved;
    }

    <T> String getModelNames(String ids, CrudRepository<T, Long> repository, String fieldName) {
        try {
            List<T> dataList = BaseUtil.getModelList(repository, ArrayStringUtil.getStringIds(ids));
            return FieldArrayUtil.getFieldStr(dataList, fieldName);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    String getModelProvinceStr(String provinces, NationRepository repository, String fieldName) {
        try {
            List<Nation> tList = new ArrayList<>();
            if (StringUtils.isNotEmpty(provinces)) {
                for (String province : provinces.split(",")) {
                    Nation n = repository.selectByProvince(province);
                    if (n == null) {
                        logger.info("省份未找到，名称为:" + province);
                        continue;
                    }
                    tList.add(n);
                }
            }
            return FieldArrayUtil.getFieldStr(tList, fieldName);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    private JsonResponse create_saveUser(User user, UserProfile userProfile, String userType, String serialNumber, String name, String telephone,
                                         String departmentIds, String proinces, String proincesAndBrands, String stationIds, String authorities, String brands, Boolean isAdmin) {
        //设置User基本信息
        if (user.getUserFlag() != null){
            if (user.getUserFlag() != -1) {
                user.setUserFlag(0);
            }else {
                user.setUserFlag(2);
            }
        }else{
            user.setUserFlag(1);
        }
        user.setUsername(telephone);
        user.setPassword(passwordEncoder.encode(Constants.INIT_PASSWORD));
        user.setUserType(UserType.valueOf(userType));
        userProfile.setTelephone(telephone);
        userProfile.setSerialNumber(serialNumber);
        String oldName = userProfile.getRealName();
        userProfile.setRealName(name);

        //封装所属部门 并设置进userProfile
        List<Long> departmentIdList = changeToLong(departmentIds);
        List<Department> departmentList = new ArrayList<>();
        for (Long id : departmentIdList) {
            Department department = departmentRepository.findOne(id);
            if (department == null) {
                logger.info("部门未找到，编号为:" + id);
                continue;
            }
            departmentList.add(department);
        }
        userProfile.setDepartmentList(new ArrayList<Department>());
        userProfileRepository.save(userProfile);
        userProfile.setDepartmentList(departmentList);

        //判断省份是否为空 不为空则封装省份
        //先清空省份
        List<Nation> nationList = new ArrayList<>();
        String[] proincesArray = proinces.split(",");
        for (String nation : proincesArray) {
            if (StringUtils.isNotEmpty(nation)) {
                Nation n = nationRepository.selectByProvince(nation);
                if (n == null) {
                    logger.info("省份未找到，名称为:" + nation);
                    continue;
                }
                nationList.add(n);
            }

        }

        userProfile.setNationList(nationList);

        //判断负责的品牌是否为空 不为空则设置负责的品牌
        userProfile.setProincesAndBrands(proincesAndBrands);

        //判断/封装维修站 不为空则设置进userProfile
        if (StringUtils.isNotEmpty(stationIds)) {
            List<Long> stationIdList = changeToLong(stationIds);
            List<Station> stationList = new ArrayList<>();
            for (Long id : stationIdList) {
                Station station = stationRepository.findOne(id);
                if (station == null) {
                    logger.info("维修站未找到，编号为:" + id);
                    continue;
                }
                stationList.add(station);
            }
            userProfile.setStationList(stationList);
        } else {
            userProfile.setStationList(null);
        }


        //判断/封装权限功能 不为空则设置进User
        List<Long> authoritiesIdList = changeToLong(authorities);
        Set<ModuleAuthority> moduleAuthoritySet = new HashSet<>();
        for (Long id : authoritiesIdList) {
            ModuleAuthority moduleAuthority = moduleAuthorityRepository.findOne(id);
            if (moduleAuthority == null) {
                logger.info("权限功能未找到，编号为:" + id);
                continue;
            }
            moduleAuthoritySet.add(moduleAuthority);
        }
        user.setAuthorities(moduleAuthoritySet);

        //判断所选的汽车品牌是否为空
        List<Long> brandIdList = changeToLong(brands);
        List<Brand> brandList = new ArrayList<>();
        for (Long id : brandIdList) {
            Brand brand = brandRepository.findOne(id);
            if (brand == null) {
                logger.info("汽车品牌未找到，编号为:" + id);
                continue;
            }
            brandList.add(brand);
        }
        userProfile.setBrandList(brandList);

        if (null != isAdmin) {
            user.setRole(isAdmin?0:1);
            userProfile.setAdmin(isAdmin);
        }

        try {
            userRepository.save(user);
            userProfile.setUser(user);
            userProfileRepository.save(userProfile);
            ChangePerformaceEmployeeName(name, oldName);
            return JsonResponse.successResponse();
        } catch (Exception e) {
            return JsonResponse.errorResponseWithError("抱歉", "执行失败");
        }
    }

    private void ChangePerformaceEmployeeName(String name, String oldName) {
        if (!name.equals(oldName)) {
                List<PerformanceReport> performanceReports = performanceReportRepository.findByEmployeeName(oldName);

                if (performanceReports != null && performanceReports.size() > 0) {
                    for (PerformanceReport performanceReport : performanceReports) {
                        performanceReport.setEmployeeName(name);
                        performanceReportRepository.save(performanceReport);
                    }
                }
                List<PerformanceReport> performanceReportUsers = performanceReportRepository.findByUserName(oldName);
                if (performanceReportUsers != null && performanceReportUsers.size() > 0) {
                    for (PerformanceReport performanceReport : performanceReportUsers) {
                        performanceReport.setUserName(name);
                        performanceReportRepository.save(performanceReport);
                    }
                }
             List<PerformanceReportRecord> performanceReportRecords = performanceReportRecordRepository.findByEmployeeName(oldName);
             if (performanceReportRecords != null && performanceReportRecords.size() > 0) {
                 for (PerformanceReportRecord performanceReportRecord : performanceReportRecords) {
                     performanceReportRecord.setEmployeeName(name);
                     performanceReportRecordRepository.save(performanceReportRecord);
                 }
             }
             List<PerformanceReportDetail> performanceReportDetails = performanceReportDetailRepository.findByEmployeeName(oldName);
             if (performanceReportDetails != null && performanceReportDetails.size() > 0) {
                 for (PerformanceReportDetail performanceReportDetail : performanceReportDetails) {
                     performanceReportDetail.setEmployeeName(name);
                     performanceReportDetailRepository.save(performanceReportDetails);
                 }
             }
        }
    }

    private List<Long> changeToLong(String values) {
        String[] valueArray = values.split(",");
        List<Long> id = new ArrayList<>();
        for (String value : valueArray) {
            if (StringUtils.isNotEmpty(value)) {
                try {
                    id.add(Long.valueOf(value));
                } catch (Exception e) {
                    logger.info("格式转换错误：" + value);
                    continue;
                }
            }
        }
        return id;
    }


}
